import { Transfer, Tree } from 'antd';
import React, { FC, useEffect, useState } from 'react';


// Customize Table Transfer
const isChecked = (selectedKeys, eventKey) => {
    return selectedKeys.indexOf(eventKey) !== -1;
};



const generateTree = (treeNodes = [], checkedKeys = []):any => {
    return treeNodes.map(({ children, ...props }) =>{
        let key = props.key+'';
        if (key.indexOf('_')) {
            key = key.split('_')[key.split('_').length-1]
        }
        return ({
            ...props,
            disabled: checkedKeys.includes(Number(key)),
            children: generateTree(children, checkedKeys),
        })
    });
};

const TreeTransfer = ({ dataSource, targetKeys, onLoadData, transferDataSource, ...restProps }) => {
    return (
        <Transfer
            {...restProps}
            targetKeys={targetKeys}
            dataSource={transferDataSource}
            className="tree-transfer"
            render={item => item.title}
            showSelectAll={false}
            oneWay
        >
            {({ direction, onItemSelect, selectedKeys }) => {
                if (direction === 'left') {
                    const checkedKeys = [...selectedKeys, ...targetKeys];
                    return (
                        <Tree
                            // loadData={onLoadData}
                            blockNode
                            checkable
                            // checkStrictly
                            checkedKeys={checkedKeys}
                            treeData={generateTree(dataSource, targetKeys)}
                            onCheck={(_, { node: { key } }) => {
                                onItemSelect(key, !isChecked(checkedKeys, key));
                            }}
                            onSelect={(_, { node: { key } }) => {
                                onItemSelect(key, !isChecked(checkedKeys, key));
                            }}
                        />
                    );
                }
            }}
        </Transfer>
    );
};

export default TreeTransfer;